package com.atguigu.gmall.rabbitmq.config;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.rabbitmq.pojo.GmallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author: Mamba
 * @version: 1.0
 * @Time: 2021/1/11 0:08
 * @Description:
 *
 * MQ生产者 应答配置实现类
 */
@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,
        RabbitTemplate.ReturnCallback{
    //注入
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init(){
        this.rabbitTemplate.setConfirmCallback(this);
        this.rabbitTemplate.setReturnCallback(this);
    }

    //交换机应答实现类
    // 成功与失败都应答
    //参数1： CorrelationData ： 消息发送的时候相关信息
    //参数2：ack : true 成功   false:失败
    //参数3： 成功应答 cause null 失败应答：失败的原因  404 NOT FOUND no exchange
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        System.out.println("ack:" + ack);
        if (ack){
            //成功
            log.info("交换机发送成功:ack:"+ack+":cause:"+cause);
        }else {
            //失败了 记录
            log.info("交换机发送失败:ack:"+ack+":cause:"+cause);
            //重新发送
            this.retrySendMessage(correlationData);
        }
    }
    //重新发送
    private void retrySendMessage(CorrelationData correlationData){
        GmallCorrelationData gmallCorrelationData = (GmallCorrelationData) correlationData;
      int retryCount = gmallCorrelationData.getRetryCount();
      if (retryCount++ <3){
          gmallCorrelationData.setRetryCount(retryCount);
          //缓存
          redisTemplate.opsForHash().put(
                  "rabbit:message",correlationData.getId(),
                  JSONObject.toJSONString(gmallCorrelationData));
          //重新发送
          rabbitTemplate.convertAndSend(gmallCorrelationData.getExchange(),
                  gmallCorrelationData.getRoutingKey(),gmallCorrelationData.getMessage(),
                  gmallCorrelationData);
      }else {
          log.info("重新发送次数用完，请管理员来处理！"+ JSONObject.toJSONString(gmallCorrelationData));
      }
    }

    //队列应答实现类
    //只能失败了才应答
    //参数1：Message ： 发送消息  消息头及体
    //参数2   replyCode : 失败码 404
    //参数3   replyCode : 失败英文说明  NOT Found
    //参数4  交换机
    //参数5   队列
    @Override
    public void returnedMessage(Message message, int replyCode,
                                String replyText, String exchange,
                                String routingKey) {
        //肯定失败了
        Object uuid = message.getMessageProperties().getHeader("spring_returned_message_correlation");

        String o = (String) redisTemplate.opsForHash().get("rabbit:message", uuid);
        GmallCorrelationData gmallCorrelationData = JSONObject.parseObject(o, GmallCorrelationData.class);
//        if (gmallCorrelationData.isDelay()){
//            System.out.println("不要重新发：是延迟插件造成的");
//            return;
//        }
        System.out.println("开始重新发送");
        //重新发送
        this.retrySendMessage(gmallCorrelationData);
    }
}
